package com.funmi.lizip.common.base;

import com.funmi.lizip.common.exception.ApplicationException;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 *  @author wangdc
 *  @since 2022-11-02
 */
public class BeanToArrayUtil {

    /**
     * 获取对象属性值转成Array
     * @param bean
     * @return
     */
    public static Object[] getFieldBeans(Object bean) {
        Map<String, Object> map = beanToArray(bean);
        return map.values().toArray(new Object[map.size()]);
    }

    /**
     * 获取对象属性转成Array
     * @param bean
     * @return
     */
    public static String[] getFieldNames(Object bean) {
        Map<String, Object> map = beanToArray(bean);
        return map.keySet().toArray(new String[map.size()]);
    }

    /**
     * 获取对象转成Array
     * @param bean
     * @return
     */
    public static Map<String, Object> beanToArray(Object bean){
        Field[] fields = bean.getClass().getDeclaredFields();
        Map<String , Object> map = new HashMap<>();
        Field.setAccessible(fields,true);
        for (Field field: fields) {
            try {
                if (field.get(bean) == null) {
                    continue;
                }
                map.put(field.getName(), field.get(bean));
            } catch (IllegalAccessException e) {
                throw new ApplicationException("对象转数组失败");
            }
        }
        return map;
    }
}
